

const screenWidth = window.innerWidth
const screenHeight = window.innerHeight

import global from './global'
import Sprite from './sprite'
import Bullet from './bullet'

/**
 * 玩家，战机
 */
export default class Player extends Sprite{

  constructor() {
    super('images/hero.png' , 80, 80)
    this.top = 0
    this.reset()
    this.initEvent()
  }

  initEvent() {
    canvas.addEventListener('touchstart', ((e) => {
      e.preventDefault()
      let x = e.touches[0].clientX
      let y = e.touches[0].clientY
      // 判断是否在范围内
      let onX = x >= this.x && x <= this.x  + this.width
      let onY = y >= this.y && y <= this.y + this.height
      if(onX && onY){
        this.touched = true
      }

    }).bind(this))

    canvas.addEventListener('touchmove', ((e) => {
      e.preventDefault()
      let x = e.touches[0].clientX
      let y = e.touches[0].clientY
      if (this.touched){
        this.x = x - this.width/2
        this.y = y - this.height/2
      }

    }).bind(this))

    canvas.addEventListener('touchend', ((e) => {
      e.preventDefault()
      this.touched = false
    }).bind(this))
  }

  reset() {
    this.x = (screenWidth - this.width) / 2
    this.y = screenHeight - 100
  }

  update() {
  }

  render(ctx) {
    ctx.drawImage(
      this.img, this.x , this.y , this.width, this.height
    )
  }

  /**
 * 玩家射击操作
 * 射击时机由外部决定
 */
  shoot() {
    let bullet = new Bullet()
    bullet.init(
      this.x + (this.width - bullet.width) / 2,
      this.y - 10,
      10
    )
    global.bullets.push(bullet)
  }
}
